import auth from '@/service/auth';
import storage from '@/libs/storage';
import loading from '@/components/globalLoading'

export default {
  auth(to, from, next) {
    const query = to.query;
    const {
      marketChannel,
      channel,
      appName,
      appVersion,
      company,
      source,
      appPackage,
      domain,
      utmSource,
      utmMedium,
      version,
      deviceId,
      installTime,
      crossUser,
      fireToken,
      afid
    } = query;
   
    if (marketChannel && marketChannel !== 'undefined' && marketChannel !== 'null') storage.set('marketChannel', marketChannel);
    if (channel && channel !== 'undefined' && channel !== 'null') storage.set('channel', channel);
    if (appName && appName !== 'undefined' && appName !== 'null') storage.set('appName', decodeURIComponent(appName));
    if (appVersion && appVersion !== 'undefined' && appVersion !== 'null') storage.set('appVersion', decodeURIComponent(appVersion));
    if (company && company !== 'undefined' && company !== 'null') storage.set('company', decodeURIComponent(company));
    if (source && source !== 'undefined' && source !== 'null') storage.set('source', decodeURIComponent(source));
    if (appPackage && appPackage !== 'undefined' && appPackage !== 'null') storage.set('appPackage', decodeURIComponent(appPackage));
    if (domain && domain !== 'undefined' && domain !== 'null') storage.set('domain', decodeURIComponent(domain));
    if (utmSource && utmSource !== 'undefined' && utmSource !== 'null') storage.set('utmSource', decodeURIComponent(utmSource));
    if (utmMedium && utmMedium !== 'undefined' && utmMedium !== 'null') storage.set('utmMedium', decodeURIComponent(utmMedium));
    // if (query.code) {
    //   storage.set('user', {
    //     code: query.code || '',
    //     phone: query.phone || '',
    //     userId: query.userId || ''
    //   });
    // }
    if (version) storage.set('version', version || '1.0.0');
    if (deviceId) storage.set('deviceId', deviceId || '');
    if (installTime) storage.set('installTime', installTime || null)
    if (afid) storage.set('afid', afid || null)
    // 为埋点新增 
    if (crossUser) storage.set('crossUser', crossUser || null);
    //  为下单新增
    if (fireToken) storage.set('fireToken', fireToken || null)
    loading.open()
    if (to.matched.some(record => record.meta.requiresAuth)) {
      auth.loggedIn().then(() => {
        next();
      }).catch(() => {
        next({ path: '/login', query: { redirectUrl: to.fullPath } });
      });
    } else {
      next(); // 确保一定要调用 next()
    }
  }
};
